package com.sna.snaapplication.controller.Captcha;

import com.sna.snaapplication.service.Captcha.CaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import jakarta.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("/api")
public class CaptchaController {
    
    @Autowired
    private CaptchaService captchaService;
    
    @GetMapping(value = "/captcha", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] getCaptcha(HttpServletRequest request) throws IOException {
        // 生成验证码文本
        String captchaCode = captchaService.generateCaptchaCode();
        // 生成验证码图片
        BufferedImage captchaImage = captchaService.generateCaptchaImage(captchaCode);
        // 存储验证码
        captchaService.storeCaptcha(request, captchaCode);
        
        // 转换为字节数组返回
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(captchaImage, "jpg", outputStream);
        return outputStream.toByteArray();
    }
}